#!/bin/bash

# autosshfs-user -- Manage users who can automount SSHFS with their ssh-agent
#
## LICENSE
#
# Copyright 2011,2012,2013 hellekin <hellekin@cepheide.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>,
# or, from the package source directory, run: make license
#

PROGNAME=${0##*/}

PREFIX="%PREFIX%"
GROUP="%GROUP%"

fail() {
  echo "${PROGNAME}: $@"
  exit 1
}

usage() {
  echo "${PROGNAME} [add|del] username"
}

if [[ $# -ne 2 ]]; then
  usage; exit 1
fi

if [ "$(id -un)" != "root" ]
then
  echo "${PROGNAME} must be run as root"
  usage; exit 1
fi

username="${2}"
test -n "${username}" || fail "second argument must be a username"

uid=$(id -u $username)
test $? -eq 0 || fail "unknown user"
gid=$(id -g $username)
test $? -eq 0 || fail "user has no primary group?"

# Do some magic to sanitize environment
mountroot="/home/${username}/mnt/ssh"
test -d "${mountroot}" || mkdir -p -m 0755 "${mountroot}" || true
su - $username -c "test -O ${mountroot} -a -G ${mountroot}" || chown ${uid}:${gid} "${mountroot}"
chmod 0700 "${mountroot}"

master_line="${mountroot} program:${PREFIX}/sbin/autosshfs-map uid=${uid},gid=${gid},workaround=rename,--timeout=600,--ghost"

SSH_WRAPPER="${PREFIX}/bin/autosshfs-as-${username}"

create_ssh_wrapper() {
  local generator="# Generated by ${PROGNAME} at $(date -R)"

cat > ${SSH_WRAPPER} <<EOD
#!/bin/sh
#
# autosshfs-as-${username}
#
# Wrapper script to make automount use the user's ssh-agent(1)
# when mounting SSHFS.  It is used as the ssh-command by autofs(8).
#

if [ \`id -un\` != "root" ]; then
  logger -s -i -t autosshfs "user \${USER} is not authorized to run autosshfs-as-${username}"
  exit 1
fi

# automount(8) sends -a -x -oClearAllForwardings=yes -2 HOST -s sftp
exec sudo -H -u ${username} -i ${PREFIX}/sbin/autosshfs-ssh "\${5}"
${generator}
EOD
}

case "$1" in
  add)
    adduser $username $GROUP
    create_ssh_wrapper
    if grep "^$mountroot" /etc/auto.master 2>/dev/null
    then
      sed -e "s#${mountroot}.*#$master_line#" -i /etc/auto.master
    else
      echo "$master_line" >> /etc/auto.master
    fi
    ;;
  del)
    rm -f $SSH_WRAPPER
    deluser $username $GROUP
    sed -e "s#${mountroot}.*##" -i /etc/auto.master
    ;;
  *)
    usage
    exit 1
    ;;
esac

restart autofs 2>/dev/null || /etc/init.d/autofs restart
